﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using RuoYi.Framework.Authorization.Handlers;

namespace RuoYi.Framework.Authorization;

/// <summary>
/// 策略授权服务拓展类
/// Authorization (授权)
/// 作用：确定已认证用户可以访问哪些资源，解决"你能做什么"的问题。
/// </summary>
[SuppressSniffer]
public static class AuthorizationServiceCollectionExtensions
{
    /// <summary>
    /// 添加策略授权服务
    /// </summary>
    /// <typeparam name="TAuthorizationMiddlewareResultHandler">策略授权处理程序</typeparam>
    /// <param name="services">服务集合</param>
    /// <param name="configure">自定义配置</param>
    /// <param name="enableGlobalAuthorize">是否启用全局授权</param>
    /// <returns>服务集合</returns>
    public static IServiceCollection AddAppAuthorization<TAuthorizationMiddlewareResultHandler>(this IServiceCollection services, Action<IServiceCollection> configure = null, bool enableGlobalAuthorize = false)
        where TAuthorizationMiddlewareResultHandler : class, IAuthorizationMiddlewareResultHandler
    {
        // 注册授权策略提供器
        services.TryAddSingleton<IAuthorizationPolicyProvider, AppAuthorizationPolicyProvider>();

        // 注册策略授权处理程序(直接返回不做校验)
        services.TryAddSingleton<IAuthorizationHandler, NoAuthorizationHandler>();

        // 注册策略授权处理程序(真正校验)
        services.TryAddSingleton<IAuthorizationMiddlewareResultHandler, TAuthorizationMiddlewareResultHandler>();

        //启用全局授权
        if (enableGlobalAuthorize)
        {
            services.Configure<MvcOptions>(options =>
            {
                options.Filters.Add(new AuthorizeFilter());
            });
        }

        configure?.Invoke(services);
        return services;
    }
}